import { computed } from 'vue'
import { useAuthStore } from '@/stores/auth'

export function usePermission() {
  const authStore = useAuthStore()

  const hasPermission = (permission: string): boolean => {
    if (!authStore.user || !authStore.permissions) {
      return false
    }

    // 超级管理员拥有所有权限
    if (authStore.user.roles?.some(role => role.name === 'ADMIN')) {
      return true
    }
    // 检查用户是否有指定权限
    return authStore.permissions.includes(permission)
  }

  const hasAnyPermission = (permissions: string[]): boolean => {
    return permissions.some(permission => hasPermission(permission))
  }

  const hasAllPermissions = (permissions: string[]): boolean => {
    return permissions.every(permission => hasPermission(permission))
  }

  const hasRole = (roleName: string): boolean => {
    if (!authStore.user || !authStore.user.roles) {
      return false
    }
    return authStore.user.roles.some(role => role.name === roleName)
  }

  return {
    hasPermission,
    hasAnyPermission,
    hasAllPermissions,
    hasRole,
    permissions: computed(() => authStore.permissions || []),
    roles: computed(() => authStore.user?.roles || [])
  }
}